package com.jztd.servone.invoice.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.xbatis.core.sql.executor.chain.UpdateChain;
import cn.xbatis.datasource.routing.DS;
import com.jztd.platfrom.base.util.UserUtil;
import com.jztd.servone.invoice.dto.InvoiceTitleDTO;
import com.jztd.servone.invoice.mapper.InvoiceTitleMapper;
import com.jztd.servone.invoice.param.InvoiceTitleParam;
import com.jztd.servone.invoice.po.InvoiceTitle;
import com.jztd.servone.invoice.service.InvoiceTitleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@DS("invoice")
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class InvoiceTitleServiceImpl implements InvoiceTitleService {
    private final InvoiceTitleMapper invoiceTitleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createInvoiceTitle(InvoiceTitleParam param) {
        InvoiceTitle invoiceTitle = Convert.convert(InvoiceTitle.class, param);
        invoiceTitle.setUserId(UserUtil.getUserId());
        invoiceTitle.setDeleted(0L);
        invoiceTitle.setTenant(UserUtil.getTenant());
        // 如果设置为默认抬头，先取消其他默认抬头
        if (ObjectUtil.isNotEmpty(invoiceTitle.getDefaultTitle()) && invoiceTitle.getDefaultTitle()) {
            UpdateChain.of(invoiceTitleMapper)
                    .update(InvoiceTitle.class)
                    .set(InvoiceTitle::getDefaultTitle, 0)
                    .eq(InvoiceTitle::getUserId, UserUtil.getUserId())
                    .execute();
        } else {
            invoiceTitle.setDefaultTitle(false);
        }
        int i = invoiceTitleMapper.save(invoiceTitle);
        return i > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteInvoiceTitle(Long id) {
        InvoiceTitle invoiceTitle = invoiceTitleMapper.getById(id);
        if (invoiceTitle == null) {
            throw new IllegalArgumentException("发票抬头不存在");
        }
        int rows = invoiceTitleMapper.deleteById(id);
        return rows > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateInvoiceTitle(InvoiceTitleParam param) {
        try {
            InvoiceTitle existingTitle = invoiceTitleMapper.getById(param.getId());
            if (existingTitle == null) {
                throw new IllegalArgumentException("发票抬头不存在");
            }
            // 如果设置为默认抬头，先取消其他默认抬头
            if (param.getDefaultTitle() && !existingTitle.getDefaultTitle()) {
                UpdateChain.of(invoiceTitleMapper)
                        .update(InvoiceTitle.class)
                        .set(InvoiceTitle::getDefaultTitle, 0)
                        .eq(InvoiceTitle::getUserId, UserUtil.getUserId())
                        .execute();
            }
            existingTitle = Convert.convert(InvoiceTitle.class, param);
            existingTitle.setDeleted(0L);
            int i = invoiceTitleMapper.update(existingTitle);
            return i > 0;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<InvoiceTitleDTO> getInvoiceTitleList() {
        List<InvoiceTitle> invoiceTitles = invoiceTitleMapper.list(where -> {
            where
                    .eq(InvoiceTitle::getUserId, UserUtil.getUserId())
                    .eq(InvoiceTitle::getTenant, UserUtil.getTenant())
                    .eq(InvoiceTitle::getDeleted, 0);
        });
        if (ObjectUtil.isEmpty(invoiceTitles)) {
            return null;
        }
        return Convert.toList(InvoiceTitleDTO.class, invoiceTitles);
    }
}
